package com.qdlc.p2p.manage.action;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.security.auth.login.AccountException;

import com.qdlc.p2p.dal.mybatis.pager.core.PageParameter;
import org.apache.struts2.convention.annotation.Action;

import com.opensymphony.xwork2.ModelDriven;
import com.qd.p2p.adapter.AdaptedRequestHandleService;
import com.qd.p2p.adapter.param.QueryBalanceParameter;
import com.qd.p2p.adapter.response.QueryBalanceResponse;
import com.qd.p2p.sina.pay.enums.AccountType;
import com.qd.p2p.sina.pay.enums.IdentityType;
import com.qd.p2p.sina.pay.response.sinaQueryBalanceResponse;
import com.qd.p2p.sina.service.SinaPayService;
import com.qdlc.p2p.biz.service.AccountService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.tpp.TppBaseInterface;
import com.qdlc.p2p.biz.tpp.TppServiceFactory;
import com.qdlc.p2p.biz.util.excel.ExcelUtils;
import com.qdlc.p2p.biz.util.excel.JsGridReportBase;
import com.qdlc.p2p.biz.util.excel.TableData;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.dto.Account;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.model.AccountModel;
import com.qdlc.p2p.dal.model.TppAccountModel;
import com.qdlc.p2p.dal.model.TppModel;
import com.qdlc.p2p.dal.mybatis.model.mapper.AccountMapper;
import com.qdlc.p2p.dal.mybatis.pager.PageProxyBuilder;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 用户账户管理
 * 
 * @author cx
 * @version 2.0
 * @since 2014-4-22
 */
public class ManageAccountAction extends BaseAction<AccountModel> implements
		ModelDriven<AccountModel> {
	@Resource
	private AccountService accountService;
	
	@Resource
	private SinaPayService sinaPayService;

	@Resource
	private UserService userService;
	
	@Resource
	private AdaptedRequestHandleService aRHService;

	private Map<String, Object> map = new HashMap<String, Object>();

	/**
	 * 用户账户页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/modules/account/account/accountManager")
	public String userCreditManager() throws Exception {
		request.setAttribute("guardFunds",accountService.sumUseMoney());
		return "accountManager";
	}
	
	/**
	 * 用户对账（托管资金差额）页面
	 * 
	 * @return
	 * @throws Exception
	 */
	@Action("/modules/account/account/tppDifference")
	public String tppDifference() throws Exception {
		return "tppDifference";
	}

	/**
	 * 用户账户列表
	 * 
	 * @throws Exception
	 */
	@Action("/modules/account/account/accountList")
	public void accountList() throws Exception {
		PageProxyBuilder<AccountMapper> builder = PageProxyBuilder.newBuilder(AccountMapper.class);
        builder.setPageParameter(model.getPage(),model.getRows());
		List<AccountModel> accountList = builder.createProxy().list(model);
		PageParameter page = builder.getPageParameter();
		map.put("total", page.getTotalCount());
		map.put("rows", accountList);
		printJson(getStringOfJpaObj(map));
	}

	/**
	 * <p>查询新浪资金</p>
	 * @author 原系统 2016年2月4日 下午4:40:28
	 * @return
	 * @throws Exception
	 * @modificationHistory=========================逻辑或功能性重大变更记录
	 * @modify by user: Kaiju Zhao 2016年2月4日 下午4:40:28
	 * @modify by reason: 消除错误和规范代码
	 */
	@Action("/modules/account/account/tppQueryUserBalance")
	public String tppQueryUserBalance() throws Exception {
		Account account = accountService.findById(model.getId());
		request.setAttribute("account", account);
		if (null == account) {
            throw new AccountException("系统不存在该账户!");
        }
		User user = UserUtils.getUserById(account.getUserId());
		if (null != user) {
            String tppUserCustId = UserUtils.getUserTppCustId(user.getUserId());
            if (!StringUtil.isBlank(tppUserCustId)) {
            	if ("baofoo".equals(SystemConfigHelper.getSystemConfig(Nid.TPP_NAME).getValue())) {// 宝付余额
            		QueryBalanceParameter parameter = new QueryBalanceParameter();
            		parameter.setPlatformUserId(tppUserCustId);
            		QueryBalanceResponse response = aRHService.queryBalance(parameter);
                    request.setAttribute("baofooBalance", response.getBalance());
            	} else {// 新浪余额
            		TppModel tppModel = new TppModel();
                    tppModel.setUser(user);
                    TppBaseInterface tppService = TppServiceFactory.newIntance();
                    TppAccountModel data = (TppAccountModel) tppService.tppQueryBalance(tppModel);
                    String bonus = data.getBonus().replace("^", "|");
                    request.setAttribute("data", data);
                    request.setAttribute("bonus", bonus);
            	}
                
            }
		}
		return "tppQueryUserBalance";
	}

	/**
	 * 查询平台新浪资金
	 *
	 * @throws IOException
	 */
	@Action("/modules/account/account/tppQueryWebBalance")
	public String tppQueryWebBalance() throws Exception {
		String tppId = SystemConfigHelper.getValue(SystemConfigHelper.Nid.MERCHANT_ID); // 平台帐号
		sinaQueryBalanceResponse response=sinaPayService.queryBalance(tppId, IdentityType.MEMBER_ID, AccountType.BASIC);
		if(response!=null&&response.success())
			request.setAttribute("availableBalance", response.getAvailableBalance());
		return "tppQueryWebBalance";
	}

	/**
	 * 导出报表
	 * 
	 * @throws Exception
	 */
	@Action("/modules/account/account/exportExcelAccount")
	public void exportExcelAccountCash() throws Exception {
		response.setContentType("application/msexcel;charset=UTF-8");

		// 第一页开始
		model.setPage(1);
		// 最多出5000条记录
		model.setRows(5000);
		model.setSort("id");
		model.setOrder("asc");
		// 记录取得
		List<AccountModel> list = accountService.list(model).getList();
		String title = "用户资金Excel表";

		String[] hearders = new String[] { "编号", "用户名", "真实姓名", "账户总额(元)",
				"可用金额(元)", "冻结总额(元)", "待收总额(元)" };// 表头数组
		String[] fields = new String[] { "id", "username", "realname",
				"totalString", "useMoneyString", "noUseMoneyString",
				"collectionString" };// 对象属性数组
		TableData td = ExcelUtils.createTableData(list,
				ExcelUtils.createTableHeader(hearders), fields);
		JsGridReportBase report = new JsGridReportBase(request, response);
		report.exportToExcel(title, getOperator().getUserName(), td);
	}
	
	@Action("/modules/account/account/huifuQueryApi")
	public String huifuQueryApi(){
		return "huifuQueryApi";
	}

	/**
	 * 获取用户的总资金与可用资金
	 */
	@Action("/modules/account/account/getMoney")
	public void getMoney() throws IOException{
		String userName=paramString("userName");
		User user=userService.getUserByInfo(userName);
		if(user==null)
			return;
		Account account = accountService.findAccountByUserId(user.getUserId());
		map.put("total",account.getTotal());
		map.put("useMoney",account.getUseMoney());
		printJson(getStringOfJpaObj(map));
	}

}
